﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace Axe.ComponentModel
{
    public class ValidatingTypeConverter : TypeConverter
    {
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(value);

            try
            {
                return converter.ConvertFrom(context, culture, value);
            }
            catch (Exception)
            {
                object oldValue = context.PropertyDescriptor.GetValue(context.Instance);
                return converter.ConvertFrom(context, culture, value);
            }
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(value);

            try
            {
                return converter.ConvertTo(context, culture, value, destinationType);
            }
            catch (Exception)
            {
                object oldValue = context.PropertyDescriptor.GetValue(context.Instance);
                return converter.ConvertTo(context, culture, value, destinationType);
            }
        }
    }
}
